package com.personal.sfe.security;

import com.personal.sfe.user.bo.UserBO;
import com.personal.sfe.user.entity.User;
import com.personal.sfe.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author: 梁奔
 * @date: 2025/11/04
 */

@Component
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private final UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUserByUserName(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found: " + username);
        }
        UserBO userBO = new UserBO();
        BeanUtils.copyProperties(user,userBO);
        List<GrantedAuthority> authorities = Stream.of("ROLE_ADMIN")
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return new CustomUserDetails(userBO, authorities);
    }
}
